# -*- coding:utf-8 -*-
# Author:Gao Xiang

import time
import pymongo
import threading
from plugin.stats import Stats

HOSTNAME = {
    'shrad000': {'host': 'xx'},
    'shard001': {'host': 'xx'},
    'shard002': {'host': 'xx'},
    'shard003': {'host': 'xx'},
    'shard004': {'host': 'xx'},
    'shard005': {'host': 'xx'},
    'shard006': {'host': 'xx'},
    'shard007': {'host': 'xx'},
    'shard008': {'host': 'xx'},
}

PORT = {
    'shrad000': 27018,
    'shard001': 27018,
    'shard002': 27018,
    'shard003': 27018,
    'shard004': 27018,
    'shard005': 27018,
    'shard006': 27018,
    'shard007': 27018,
    'shard008': 27018,
}


class MongoOp(object):

    def __init__(self, host, port):
        self.host = host
        self.port = port
        self.conn = None
        self.db = None

    # 链接到mongo并认证
    def conn_mongo(self):
        try:
            self.conn = pymongo.MongoClient(host=self.host, port=self.port)
            self.db = self.conn.get_database("admin")
            self.db.authenticate('xx', 'xx')
        except Exception as e:
            print(e)

    def op(self):
        """
        :return: len(col):当前shard的currentOp个数
        """
        col = self.db.current_op()["inprog"]
        return 'currentOp', len(col)


def send_data(hostname, host, port):
    hostname = hostname
    host = host
    port = port
    conn = MongoOp(host, port)
    conn.conn_mongo()
    while True:
        name, value = conn.op()
        stat_client = Stats(name)
        stat_client.connect()
        stat_client.send_data(hostname, value)
        # print('send', name, value)
        time.sleep(10)


def client():
    clients = []
    for i in HOSTNAME:
        HOSTNAME[i]['port'] = PORT[i]
        # print(i, HOSTNAME[i]['host'], HOSTNAME[i]['port'])
        clients.append(threading.Thread(target=send_data, args=(i, HOSTNAME[i]['host'], HOSTNAME[i]['port'])))
    for start in clients:
        start.start()


if __name__ == '__main__':
    # send_data('shard001', 'xx', 27018)
    client()